#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <fstream>
#include <stdint.h>

using namespace std;

void randomGraph(vector<vector<bool> >& graph, size_t V, size_t E)
{
    double p = 2.0*E/((V-1)*V);
    srand ( time(NULL) );

    for(size_t i = 0; i< V; ++i)
        for(size_t j = 0; j<i; ++j )
        {
            double v = rand();
            if(v<p*RAND_MAX)
            {
                graph[i][j] = true;
            };
        }
}

void writeToFile(vector<vector<bool> >& graph, const string& file )
{
    std::ofstream ofile(file.c_str(), ios::binary);

    if( ofile.is_open() )
    {
        uint16_t size = graph.size();
        ofile.write(reinterpret_cast<char *>(&size),sizeof(uint16_t));
        for(uint16_t i = 0; i< graph.size(); ++i)
            for(uint16_t j = 0; j<graph.size(); ++j )
        {
            if(graph[i][j])
            {
                
                uint16_t a = i+1;
                uint16_t b = j+1;
                ofile.write(reinterpret_cast<char *>(&a),sizeof(uint16_t));
                ofile.write(reinterpret_cast<char *>(&b),sizeof(uint16_t));
			}
        }
    }
    else
    {
        cout<<"File not open!"<<endl;
    }
}

int main(int argc, char* argv[])
{
    if(argc>3)
    {
        size_t V = (size_t) atoi(argv[1]);
        size_t P = (size_t) atoi(argv[2]);
        size_t E = (V*(V-1)/2)*P/100;
        
        vector<vector<bool> > graph;
        graph.assign(V, vector<bool>(V,false));

        randomGraph(graph, V, E);
        writeToFile(graph, string(argv[3]));

    }
    else
    {
        cout<<"Invalid format"<<endl;
        cout<<"Format: "<<argv[0]<<" V Proc ot E out.txt"<<endl;
    }
    return 0;
}
